package com.yunhe.common.filter;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * <p>Description: 将 ServerContext对象存储到 ThreadLocal中</p>
 *
 */
public class ServerContextHolder {

    private static Logger logger = LoggerFactory.getLogger(ServerContextHolder.class);

    private ServerContextHolder() {
    }

    /**
     * 这里应该使用InheritableThreadLocal  原因是springCloud 的Hystrix 会导致线程隔离 （采用线程池的方式 ）
     * 如果用ThreadLocal 那么就会导致2次的Thread是不同的，因此ThreadLocal是会不相同的, 不能达到值传递的效果
     * InheritableThreadLocal 的机制能够将ParentThreadLocal 中的值复制到子线程中，因此可以使用
     */
    private static final TransmittableThreadLocal<ServerContext> ServerContext = new TransmittableThreadLocal<>();

    public static final ServerContext getContext() {
        ServerContext context = ServerContext.get();

        if (context == null) {
            logger.info("[getContext] this is indicate that context is null to new one");
            context = createEmptyContext();
            ServerContext.set(context);
        }
        return ServerContext.get();
    }

    public static final void setContext(ServerContext context) {
        Assert.notNull(context, "Only non-null ServerContext instances are permitted");
        ServerContext.set(context);
    }

    public static final ServerContext createEmptyContext() {
        return new ServerContext();
    }
}
